/*
 * bufferPool.cpp
 *
 *  Created on: 17-Sep-2011
 *      Author: amrita
 */

#include "bufferPool.h"
map<long, long> pageMap;
bufferPool::bufferPool(long memSize)
{
	int iterFrame=1;
	Frame* currentFrame;

	frameCount=memSize/FRAME_SIZE;
	bufferSize=frameCount*FRAME_SIZE*KB;
	#ifdef DEBUG
	cout<<"Frame count is "<<frameCount;
	#endif
	//allocate bufferPool memory
	buffer =(void*) malloc(bufferSize);

	//initialise the frames
	//currentFrame=getFirstFrame();
	for(iterFrame=0;iterFrame<frameCount;iterFrame++)
	{
		currentFrame = getFrameNumber(iterFrame);
	currentFrame->dirty=false;
	currentFrame->frameNumber=iterFrame;
		//currentFrame->pinCount=0;
	currentFrame->refCount=0;
	currentFrame->dbIndex=NULL;
	currentFrame->pageData[1]='\0';


	//initialise the map
	pageMap[iterFrame]=-1;

	}


}

bufferPool::~bufferPool()
{
	free(buffer);

}
Frame* bufferPool::getFirstFrame()
{
	Frame* currentFrame=(Frame*)buffer;
	return currentFrame;
}
long bufferPool::getFrameWithPageNumber(long pageNumber)
{
	bool found = false;
	    map<long,long>::iterator iterMap = pageMap.begin();
	    while(iterMap != pageMap.end())
	    {
	        found = (iterMap->second == pageNumber);
	        if(found)
	        	return iterMap->first;
	        ++iterMap;
	    }
	    return -1;
}
void bufferPool::printMap()
{
	cout<<"MAP data"<<endl;
	map<long,long>::iterator iterMap ;
	    for ( iterMap=pageMap.begin() ; iterMap != pageMap.end(); iterMap++ )
	            cout << (*iterMap).first << " => " << (*iterMap).second << endl;
}
Frame* bufferPool::getPrevFrame()
{
	Frame* currentFrame=(Frame*)buffer;
	return currentFrame;
}
Frame* bufferPool::getFrameNumber(long frameNumber){

	long offset=(frameNumber)*FRAME_SIZE;

	void* currFrame=(void *)(buffer + offset);
	Frame* currentFrame = (Frame*)currFrame;

	return currentFrame;
}
Frame* bufferPool::getFreeFrame()
{
	int iterateFrame=0;
	cout<<"getting free frame"<<endl;
	for(;iterateFrame < frameCount;iterateFrame++)
	{
		Frame* currFrame=getFrameNumber(iterateFrame);
		if(currFrame->dbIndex==NULL)
			return currFrame;
	}
	return NULL;
}
